import Vue from 'vue'
import Router from 'vue-router'

import Login from './views/login'
import FindPassword from './views/findPassword'
import ResetPassword from './views/resetPassword'
import Register from './views/register'

import Mall from './views/mall'
import MallClassify from './views/mall/classify'
import Special from './views/mall/special'
import MallInfo from './views/mall/info'
import Seckill from './views/mall/seckill'
import MallSeckillInfo from './views/mall/seckill/info'
import MallGroup from './views/mall/group'
import MallGroupInfo from './views/mall/group/info'
import MallGroupBuy from './views/mall/group/buy'
import MallGroupWin from './views/mall/group/win'
import MallDistribution from './views/mall/distribution'
import MallDistributionInfo from './views/mall/distribution/info'
import MallDiscount from './views/mall/discount'
import MallComment from './views/mall/comment'
import MallSearch from './views/mall/search'

import Me from './views/me'
import MallOrder from './views/me/order/mall'
import MallOrderInfo from './views/me/order/mall/info'
import MallOrderAfterSaleApply from './views/me/order/afterSale/apply'
import MallOrderAfterSaleInfo from './views/me/order/afterSale/info'
import MallOrderAfterSaleShipments from './views/me/order/afterSale/shipments'
import MallOrderAfferSale from './views/me/order/afterSale'
import MallOrderComment from './views/me/order/comment'
import OrderCancel from './views/me/order/cancel'
import WelfareOrder from './views/me/order/welfare'
import LiveOrder from './views/me/order/live'
import Logistics from './views/me/order/logistics'
import Shopping from './views/me/shopping'
import Address from './views/me/address'
import AddressEdit from './views/me/address/edit'
import AddressSelect from './views/me/address/select'
import MeDiscount from './views/me/discount'
// import MeGeneralize from './views/me/generalize'
import MeInvoice from './views/me/invoice'
import MeInvoiceEdit from './views/me/invoice/edit'
import MallClearing from './views/mall/clearing'
import MallGetcoupon from './views/mall/getcoupon'
import MallInvoice from './views/mall/invoice'
import Pay from './views/pay'
import PayIng from './views/pay/pay'

import Util from './utils/util'
import Account from './dll/account'

import { globalData } from './config/globalData'
// import { cookie } from 'vux'

Vue.use(Router)

const router = new Router({
  // mode: 'history',
  mode: 'hash',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/findPassword',
      name: 'findPassword',
      component: FindPassword
    },
    {
      path: '/resetPassword',
      name: 'resetPassword',
      component: ResetPassword
    },
    {
      path: '/register',
      name: 'register',
      component: Register
    },
    {
      path: '/',
      name: 'mall',
      component: Mall
    },
    {
      path: '/mall/classify',
      name: 'mallClassify',
      component: MallClassify
    },
    {
      path: '/mall/special/:topicId',
      name: 'mallSpecial',
      component: Special
    },
    {
      path: '/mall/info/:id',
      name: 'mallInfo',
      component: MallInfo
    },
    {
      path: '/mall/seckill',
      name: 'mallSeckill',
      component: Seckill
    },
    {
      path: '/mall/seckill/info/:id',
      name: 'mallSeckillInfo',
      component: MallSeckillInfo
    },
    {
      path: '/mall/group',
      name: 'mallGroup',
      component: MallGroup
    },
    {
      path: '/mall/group/info/:id',
      name: 'mallGroupInfo',
      component: MallGroupInfo
    },
    {
      path: '/mall/group/buy',
      name: 'mallGroupBuy',
      component: MallGroupBuy
    },
    {
      path: '/mall/group/win',
      name: 'mallGroupWin',
      component: MallGroupWin
    },
    {
      path: '/mall/distribution',
      name: 'mallDistribution',
      component: MallDistribution
    },
    {
      path: '/mall/distribution/info/:id',
      name: 'mallDistributionInfo',
      component: MallDistributionInfo
    },
    {
      path: '/mall/discount',
      name: 'mallDiscount',
      component: MallDiscount,
      meta: {
        id: 1
      }
    },
    {
      path: '/mall/discount',
      name: 'mallDiscountJD',
      component: MallDiscount,
      meta: {
        id: -1
      }
    },
    {
      path: '/mall/getcoupon',
      name: 'mallGetcoupon',
      component: MallGetcoupon
    },
    {
      path: '/mall/invoice',
      name: 'mallInvoice',
      component: MallInvoice
    },
    {
      path: '/mall/comment/:goods_sku',
      name: 'mallComment',
      component: MallComment
    },
    {
      path: '/mall/clearing',
      name: 'mallClearing',
      component: MallClearing
    },
    {
      path: '/mall/search',
      name: 'mallSearch',
      component: MallSearch
    },
    {
      path: '/me',
      name: 'me',
      component: Me
    },
    {
      path: '/me/order/mall',
      name: 'mallOrder',
      component: MallOrder
    },
    {
      path: '/me/order/mall/info/:id',
      name: 'mallOrderInfo',
      component: MallOrderInfo
    },
    {
      path: '/me/order/mall/aftersale/apply',
      name: 'mallOrderAfterSaleApply',
      component: MallOrderAfterSaleApply
    },
    {
      path: '/me/order/mall/aftersale/info/:id',
      name: 'mallOrderAfterSaleInfo',
      component: MallOrderAfterSaleInfo
    },
    {
      path: '/me/order/mall/aftersale/shipments/:id',
      name: 'mallOrderAfterSaleShipments',
      component: MallOrderAfterSaleShipments
    },

    {
      path: '/me/order/mall/aftersale',
      name: 'mallOrderAfferSale',
      component: MallOrderAfferSale
    },

    {
      path: '/me/order/mall/comment',
      name: 'mallOrderComment',
      component: MallOrderComment
    },

    {
      path: '/me/order/cancel',
      name: 'orderCancel',
      component: OrderCancel
    },
    {
      path: '/me/order/welfare',
      name: 'welfareOrder',
      component: WelfareOrder
    },
    {
      path: '/me/order/live',
      name: 'liveOrder',
      component: LiveOrder
    },
    {
      path: '/me/order/logistics',
      name: 'logistics',
      component: Logistics
    },
    {
      path: '/me/shopping',
      name: 'shopping',
      component: Shopping
    },
    {
      path: '/me/address',
      name: 'address',
      component: Address
    },
    {
      path: '/me/address/edit',
      name: 'addressEdit',
      component: AddressEdit
    },
    {
      path: '/me/address/select',
      name: 'addressSelect',
      component: AddressSelect
    },
    {
      path: '/me/discount',
      name: 'meDiscount',
      component: MeDiscount
    },
    // {
    //   path: '/me/generalize',
    //   name: 'meGeneralize',
    //   component: MeGeneralize
    // },
    {
      path: '/me/invoice',
      name: 'meInvoice',
      component: MeInvoice
    },
    {
      path: '/me/modifyPass',
      name: 'modifyPass',
      component: () => import('./views/me/modifyPass')
    },
    {
      path: '/me/personalInfo',
      name: 'personalInfo',
      component: () => import('./views/me/personalInfo')
    },
    {
      path: '/me/invoice/edit',
      name: 'meInvoiceEdit',
      component: MeInvoiceEdit
    },
    {
      path: '/pay/:id',
      name: 'pay',
      component: Pay
    },
    {
      path: '/pay/pay',
      name: 'payIng',
      component: PayIng
    },
    {
      path: '/me/balance',
      name: 'balance',
      component: () => import('./views/me/balance')
    },
    {
      path: '/me/balance/details',
      name: 'balanceDetails',
      component: () => import('./views/me/balance/details')
    },
    {
      path: '/me/order/invoiceDetail',
      name: 'invoiceDetail',
      component: () => import('./views/me/order/invoiceDetail')
    },
    {
      path: '/mall/video',
      name: 'video',
      component: () => import('./views/mall/video')
    },
    {
      path: '/mall/notice',
      name: 'notice',
      component: () => import('./views/mall/notice')
    },
    {
      path: '/mall/notice/detail/:id',
      name: 'noticeDetail',
      component: () => import('./views/mall/notice/detail')
    }

    // {
    //   path: '/about',
    //   name: 'about',
    //   // route level code-splitting
    //   // this generates a separate chunk (about.[hash].js) for this route
    //   // which is lazy-loaded when the route is visited.
    //   component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
    // }
  ],
  scrollBehavior (to, from, savedPosition) {
    if (to.name === 'mallInfo') {
      return { x: 0, y: 0 }
    } else {
      if (savedPosition) {
        return savedPosition
      } else {
        return { x: 0, y: 0 }
      }
    }
  }
})

// 获取三峡token
async function getToken (params) {
  let res = await Account.ticketLoginSanxia(params)
  if (res.code == 0) {
    localStorage.setItem('accesstoken', res.data.access_token)
    localStorage.setItem('userInfo', JSON.stringify(res.data.extra))
  } else {
    Vue.$vux.alert.show({
      title: '提示',
      content: res.msg,
      onHide () {
        router.push({ name: 'login' })
      }
    })
  }
}

router.afterEach((to, from) => {
  let _href = window.location.href
  if (((/abc.uleemall.com/).test(_href)) || ((/ctg.ulinkmall.com/).test(_href))) {
    window.document.title = '三峡e购员工商城'
  } else if (((/gw.ulinkmall.com/).test(_href))) {
    window.document.title = '国网商城'
  } else if (((/xbzg.ulinkmall.com/).test(_href))) {
    window.document.title = '智谷汇员工商城'
  } else if (((/cqdx.ulinkmall.com/).test(_href))) {
    window.document.title = '电信商城'
  } else {
    window.document.title = '内购商城'
  }

  // 若果是APP 会带token 不用进登录页面 否则进入登录页面
  let urlParser = Util.UrlParser() ? Util.UrlParser().usertoken : undefined
  if (urlParser) {
    let params = {
      grant_type: 'sanxia_token',
      token: urlParser
    }
    getToken(params)
  }
})

// let popstate = false;

let configData = false
router.beforeEach((to, from, next) => {
  // 退出登录 不能进入个人中心
  // if (from.name === 'login' && to.name === 'me') {
  //   router.replace('mall')
  // }
  let href = window.location.href
  let hashUrl = href.substr(href.indexOf('#'))
  let shareUrl
  if (/#\/me/.test(hashUrl) || /#\/login/.test(hashUrl) || /#\/register/.test(hashUrl) || /#\/findPassword/.test(hashUrl) || /#\/resetPassword/.test(hashUrl)) {
    shareUrl = '#'
  } else {
    shareUrl = encodeURIComponent(hashUrl)
  }
  sessionStorage.setItem('shareUrl', shareUrl)
  // let searchurl = location.search
  // if (searchurl) {
  //   location.href = (location.href).replace(searchurl, '')
  //   return
  // }
  let access_token = globalData.access_token
  if (!access_token) {
    // globalData.access_token = access_token=cookie.get("accesstoken");
    globalData.access_token = access_token = localStorage.getItem('accesstoken')
    globalData.userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  }
  // access_token不存在时，给与默认值
  if (!access_token) {
    globalData.access_token = 'default-access_token'
  }

  // if (to.name == 'login' || to.name == 'register' || to.name == 'findPassword' || to.name == 'resetPassword') {
  //   next()
  // } else if (access_token) {
  if (Util.isWeixn()) {
    // if (!configData) {

    if (to.name == 'mallInfo') {
      if (configData) {
        next()
        return
      } else {
        configData = true
        Account.getJsdkConfig().then((res) => {
          configData = false
          if (res.code == 0) {
            // eslint-disable-next-line no-undef
            wx.config({
              debug: false,
              appId: res.data.appId,
              timestamp: res.data.timeStamp,
              nonceStr: res.data.nonceStr,
              signature: res.data.signature,
              jsApiList: [
                'updateAppMessageShareData',
                'updateTimelineShareData',
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'chooseWXPay',
                'hideMenuItems',
                'hideAllNonBaseMenuItem',
                'showMenuItems',
                'menuItem:share:appMessage',
                'menuItem:share:timeline',
                'menuItem:share:qq',
                'menuItem:share:QZone'
              ]
            })
          }
        })
      }
    }

    // }
    // eslint-disable-next-line no-undef
    wx.ready(() => {
      // eslint-disable-next-line no-undef
      wx.hideAllNonBaseMenuItem()
    })
  }
  next()
  // } else {
  //   delete to.query.VNK
  //   delete from.query.VNK
  //   // next({ name: 'login', query: { ...to.query }, params: { from: to } })
  //   next()
  // }
})

export default router
